/*
 *所有关于equipmentfailurerecords类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*equipmentfailurerecordsService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Entity.DomainModels;
using System.Linq;
using VolPro.Core.Utilities;
using System.Linq.Expressions;
using VolPro.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using SMes.DbMethod.IRepositories;
using SMes.DbMethod.ViewModel;
using SMes.DbMethod.Repositories;
using System.Collections.Generic;

namespace SMes.DbMethod.Services
{
    public partial class equipmentfailurerecordsService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IequipmentfailurerecordsRepository _repository;//访问数据库
        private readonly IequipmentRepository _equipmentRepository;
        private readonly IequipmentfaultmaintenanceRepository _equipmentfaultmaintenanceRepository;
        private readonly IequipmentfailurerecordsRepository _equipmentfailurerecordsRepository;
        [ActivatorUtilitiesConstructor]
        public equipmentfailurerecordsService(
            IequipmentfailurerecordsRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IequipmentRepository equipmentRepository,
            IequipmentfaultmaintenanceRepository equipmentfaultmaintenanceRepository,
            IequipmentfailurerecordsRepository equipmentfailurerecordsRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _equipmentRepository = equipmentRepository;
            _equipmentfaultmaintenanceRepository = equipmentfaultmaintenanceRepository;
            _equipmentfailurerecordsRepository = equipmentfailurerecordsRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public async Task<WebResponseContent> AddFailureRecords(List<equipmentfailurerecords> datas)
        {
            var webResponse = new WebResponseContent();
            await _repository.AddRangeAsync(datas);
            await _repository.SaveChangesAsync();
            return webResponse.OK();
        }
        /// <summary>
        /// 故障处理
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> AddEquipmentFault(List<DetailData> datas)
        {
            //_equipmentRepository.FindFirstAsync()
            var webResponse = new WebResponseContent();
            if (datas == null || datas.Count() == 0) { return webResponse.Error("无故障数据"); }
            List<equipmentfailurerecords> eqFailureRecords = new List<equipmentfailurerecords>();
            foreach (var data in datas)
            {
                var tag = Convert.ToInt32(data.Tag);
                var eq = await _equipmentRepository.FindAsyncFirst(x => x.SerialNo == data.EquipmentCode);
                if (eq == null) return webResponse.Error($"数据库中查询不到{data.EquipmentCode}的设备编码");
                var eqFaultMaintenance = await _equipmentfaultmaintenanceRepository.FindAsyncFirst(x => x.EquipmentID == eq.EquipmentID && x.Tag == tag);
                if (eqFaultMaintenance == null) return webResponse.Error($"数据库中查询的设备编码{eq.SerialNo}故障Tag值");
               
                var eqFailureRecord = new equipmentfailurerecords()
                {
                    FailureID = Guid.NewGuid().ToString(),
                    EquipmentID = eqFaultMaintenance.EquipmentID,
                    FailureCode = eqFaultMaintenance.FaultID.ToString(),
                    FailureDescription = eqFaultMaintenance.FaultReason,
                    FailureOccurTime = DateTime.Now,
                };
                eqFailureRecords.Add(eqFailureRecord);
            }
            await _equipmentfailurerecordsRepository.AddRangeAsync(eqFailureRecords);
            await _equipmentfailurerecordsRepository.SaveChangesAsync();
#if false
            var datasFilter = datas.Select(s => new { s.EquipmentCode, s.Value }).ToList();
            var dataEqCodes = datasFilter.Select(x => x.EquipmentCode);
            var dataTags = datasFilter.Select(x => Convert.ToInt32(x.Value));
            //var eqFliters = await _equipmentRepository.FindAsync(x => dataEqCodes.Contains(x.SerialNo), x => new
            //{
            //    x.EquipmentID,
            //    x.SerialNo
            //});
            var eqFliters = await _equipmentRepository.FindAsIQueryable(x => dataEqCodes.Contains(x.SerialNo)).Select(x => new { x.EquipmentID, x.SerialNo })
                .AsNoTracking().ToListAsync();
            if (eqFliters.Count == 0) { return webResponse.Error("数据库中查询不到设备编码"); }
            //var eqFlitersCodes = eqFliters.Select(x => x.SerialNo);
            var eqFlitersIDs = eqFliters.Select(x => x.EquipmentID).ToList();
            var CheckData = dataEqCodes.Except(eqFliters.Select(x => x.SerialNo)).ToList();
            if (CheckData != null && CheckData.Count > 0)
            {
                return webResponse.Error($"设备编码{string.Join(";", CheckData)}数据库中不存在");
            }
            var eqFaultMaintenance = await _equipmentfaultmaintenanceRepository.FindAsIQueryable(x => dataTags.Contains(x.Tag)
            && eqFlitersIDs.Contains(x.EquipmentID)).AsNoTracking().ToListAsync();
            List<equipmentfailurerecords> eqFailureRecords = new List<equipmentfailurerecords>();
            foreach (var item in eqFaultMaintenance)
            {
                var eqFailureRecord = new equipmentfailurerecords()
                {
                    FailureID = Guid.NewGuid().ToString(),
                    EquipmentID = item.EquipmentID,
                    FailureCode = item.FaultID.ToString(),
                    FailureDescription = item.FaultReason,
                    FailureOccurTime = DateTime.Now,
                };
                eqFailureRecords.Add(eqFailureRecord);
            }
            await _equipmentfailurerecordsRepository.AddRangeAsync(eqFailureRecords);
            await _equipmentfailurerecordsRepository.SaveChangesAsync();
#endif
            webResponse.OK("设备故障添加成功");
            webResponse.Code = "200";
            return webResponse;
            //foreach (var data in datas)
            //{
            //    //_equipmentRepository.FindFirstAsync
            //    // _equipmentRepository.FindAsyncFirst
            //    var eqID = await _equipmentRepository.FindFirstAsync(x => x.SerialNo == data.EquipmentCode, x => x.EquipmentID);
            //    if (eqID == null) return webResponse.Error($"设备编码:{data.EquipmentCode}不存在");
            //    var eqFaultMaintenance = await _equipmentfaultmaintenanceRepository.FindFirstAsync(x => x.EquipmentID == eqID
            //     && x.Tag == Convert.ToInt32(data.Value), x => new
            //     {
            //         x.FaultID,
            //         x.EquipmentID,
            //         x.Tag,
            //         x.FaultReason
            //     });
            //}
            return new WebResponseContent();
        }
    }
}
